//
//  Config.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/19.
//

import Foundation
import Vapor
import FluentKit
//用户登录名称 xusi1508@1210158785763975.onaliyun.com
//登录密码 enghou123
//AccessKey ID LTAI5tMgoSsCwNcuBtpJZKz3
//AccessKey Secret dyKUEFgyamFWickqPPypqFYr4nmluB
struct Config: RouteCollection {
    func boot(routes: any RoutesBuilder) throws {
        routes
            .grouped("config")
            .get("index", use: self.index)
    }
    
    struct AppConfig: Content {
        let OSSAppKey: String
        let OSSAppSecret: String
        let OSSBucket: String
        let OSSRegion: String
        let OSSEndPoint: String
        let IMServer: String
        let IMServerApi: String
        let IMUserToken: String
    }
    
    @Sendable
    func index(request: Request) async throws -> JSONResponse<AppConfig> {
        //在获取配置的时候，就应该着手创建用户
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        let language = headers["language"].first ?? ""
        if let user = try await UserModel.query(on: request.db)
            .filter(\.$id, .equal, deviceID)
            .first() {
            user.loginDate = Date()
            user.online = true
            try await user.save(on: request.db)
        } else {
            //这个用户还没注册
            let user = UserModel()
            let date = Date()
            user.loginDate = date
            user.id = deviceID
            user.deviceID = deviceID
            user.language = language
            user.name = "用户" + String.inviteCode
            user.avatar = "https://www.tracecare.cn/2E336711-D7A3-4743-85DD-8F570B87FB92_file"
            user.phone = ""
            user.online = true
            
            try await user.save(on: request.db)
        }
        let token = try await request.application.imClient.registUser(userID: deviceID)?.token ?? ""
        let imServer = Environment.get("OpenIM_Server") ?? ""
        let imServerApi = Environment.get("OpenIM_Server_API") ?? ""
        return JSONResponse(message: "", code: 0, data: AppConfig(OSSAppKey: "", OSSAppSecret: "", OSSBucket: "", OSSRegion: "", OSSEndPoint: "", IMServer: imServer, IMServerApi: imServerApi, IMUserToken: token))
    }
    
}
